<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 签到业务逻辑
 */
class Checkin extends LogicBase
{
    /**
     * 获取签到记录搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 用户ID筛选
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 时间范围筛选
        !empty($data['start_time']) && $where['checkin_date'] = ['>=', $data['start_time']];
        !empty($data['end_time']) && $where['checkin_date'] = ['<=', $data['end_time']];
        
        // 连续签到天数筛选
        if (isset($data['min_days']) && $data['min_days'] !== '') {
            $where['continuous_days'] = ['>=', $data['min_days']];
        }
        if (isset($data['max_days']) && $data['max_days'] !== '') {
            if (isset($where['continuous_days'])) {
                $where['continuous_days'] = ['between', [$data['min_days'], $data['max_days']]];
            } else {
                $where['continuous_days'] = ['<=', $data['max_days']];
            }
        }
        
        // 搜索条件：用户昵称
        !empty($data['search_data']) && $where['user_nickname'] = ['like', '%'.$data['search_data'].'%'];
        
        return $where;
    }
    
    /**
     * 获取签到记录列表
     */
    public function getCheckinList($where = [], $field = true, $order = 'checkin_date desc', $paginate = DB_LIST_ROWS)
    {
        // 排除已删除的记录
        $where[DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        return $this->modelCheckinRecord->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 签到记录添加
     */
    public function checkinAdd($data = [])
    {
        // 验证数据
        $validate_result = $this->validateCheckin->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateCheckin->getError()];
        }
        
        // 处理数据
        $data['checkin_date'] = date('Y-m-d');
        // create_time和update_time由系统自动处理
        
        $result = $this->modelCheckinRecord->setInfo($data);
        
        $result && action_log('新增', '签到记录新增，user_id：' . $data['user_id']);
        
        return $result ? [RESULT_SUCCESS, '签到记录添加成功'] : [RESULT_ERROR, $this->modelCheckinRecord->getError()];
    }
    
    /**
     * 签到记录编辑
     */
    public function checkinEdit($data = [])
    {
        $validate_result = $this->validateCheckin->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateCheckin->getError()];
        }
        
        // update_time由系统自动处理
        
        $result = $this->modelCheckinRecord->setInfo($data);
        
        $result && action_log('编辑', '签到记录编辑，id：' . $data['id']);
        
        return $result ? [RESULT_SUCCESS, '签到记录编辑成功'] : [RESULT_ERROR, $this->modelCheckinRecord->getError()];
    }
    
    /**
     * 签到记录删除
     */
    public function checkinDel($data = [])
    {
        $where = ['id' => $data['id']];
        
        $result = $this->modelCheckinRecord->deleteInfo($where);
        
        $result && action_log('删除', '签到记录删除，id：' . $data['id']);
        
        return $result ? [RESULT_SUCCESS, '签到记录删除成功'] : [RESULT_ERROR, $this->modelCheckinRecord->getError()];
    }
    
    /**
     * 签到记录状态切换
     */
    public function checkinStatus($data = [])
    {
        $where = ['id' => $data['id']];
        $update = ['status' => $data['status']]; // update_time由系统自动处理
        
        $result = $this->modelCheckinRecord->updateInfo($where, $update);
        
        $result && action_log('状态', '签到记录状态切换，id：' . $data['id'] . '，status：' . $data['status']);
        
        return $result ? [RESULT_SUCCESS, '状态切换成功'] : [RESULT_ERROR, $this->modelCheckinRecord->getError()];
    }
    
    /**
     * 签到记录导出
     */
    public function exportCheckinList($where = [])
    {
        $list = $this->getCheckinList($where, true, 'checkin_date desc', false);
        
        // 导出逻辑
        // TODO: 实现Excel导出功能
        
        return [RESULT_SUCCESS, '导出成功'];
    }
    
    /**
     * 获取签到统计
     */
    public function getCheckinStats($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $days = $data['days'] ?? 30;
        
        try {
            $startTime = date('Y-m-d', time() - ($days * 86400));
            $endTime = date('Y-m-d');
            
            $where = [
                'checkin_date' => ['between', [$startTime, $endTime]]
            ];
            
            if ($userId) {
                $where['user_id'] = $userId;
            }
            
            // 获取签到统计
            $totalCheckins = $this->modelCheckinRecord->stat($where, 'count');
            $totalUsers = $this->modelCheckinRecord->stat($where, 'count', 'DISTINCT user_id');
            $maxContinuous = $this->modelCheckinRecord->getValue($where, 'MAX(continuous_days)') ?: 0;
            $avgContinuous = $this->modelCheckinRecord->getValue($where, 'AVG(continuous_days)') ?: 0;
            
            $data = [
                'total_checkins' => $totalCheckins,
                'total_users' => $totalUsers,
                'max_continuous' => $maxContinuous,
                'avg_continuous' => round($avgContinuous, 2),
                'days' => $days
            ];
            
            return $data;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取签到统计失败：' . $e->getMessage());
            return [RESULT_ERROR, '获取签到统计失败'];
        }
    }
    
    /**
     * 获取用户签到状态
     */
    public function getUserCheckinStatus($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        try {
            $today = date('Y-m-d');
            $yesterday = date('Y-m-d', time() - 86400);
            
            // 检查今天是否已签到
            $todayCheckin = $this->modelCheckinRecord->getInfo([
                'user_id' => $userId,
                'checkin_date' => $today
            ]);
            
            // 获取最近的签到记录
            $lastCheckin = $this->modelCheckinRecord->getInfo([
                'user_id' => $userId
            ], true, 'checkin_date desc');
            
            $continuousDays = 0;
            if ($lastCheckin) {
                if ($lastCheckin['checkin_date'] == $today) {
                    $continuousDays = $lastCheckin['continuous_days'];
                } elseif ($lastCheckin['checkin_date'] == $yesterday) {
                    $continuousDays = $lastCheckin['continuous_days'];
                }
            }
            
            $data = [
                'is_checkin_today' => !empty($todayCheckin),
                'continuous_days' => $continuousDays,
                'last_checkin_date' => $lastCheckin ? $lastCheckin['checkin_date'] : '',
                'can_checkin' => empty($todayCheckin)
            ];
            
            return $data;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取用户签到状态失败：' . $e->getMessage());
            return [RESULT_ERROR, '获取用户签到状态失败'];
        }
    }
    
    /**
     * 重置用户签到记录
     */
    public function resetUserCheckin($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        try {
            $where = ['user_id' => $userId];
            $result = $this->modelCheckinRecord->deleteInfo($where, true);
            
            $result && action_log('重置', '重置用户签到记录，user_id：' . $userId);
            
            return $result ? [RESULT_SUCCESS, '重置签到记录成功'] : [RESULT_ERROR, '重置签到记录失败'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('重置用户签到记录失败：' . $e->getMessage());
            return [RESULT_ERROR, '重置签到记录失败'];
        }
    }
}